package com.controller.common;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;


public class CommonController {
	private static Logger logger = LoggerFactory.getLogger(CommonController.class);

	/**
	 * Spring会默认注入当前线程的HttpServletRequest
	 */
	@Autowired
	protected HttpServletRequest request;

	/**
	 * 从请求json参数中抽取param值
	 * 
	 * @param incomeJson
	 * @return
	 */
	protected JSONObject getParamJson(JSONObject incomeJson) {
		String paramStr = incomeJson.getString("param");

		if (StringUtils.isEmpty(paramStr)) {
			return null;
		}
		return JSONObject.parseObject(paramStr);
	}

	/***
	 * 获取客户端IP地址
	 * 这里通过了Nginx获取;X-Real-IP,X-Forwarded-For
	 * @param request
	 * @return
	 */
	public String getClientIP() {
		String ip = request.getHeader("X-Real-IP");
		if (ip == null || ip.length() == 0) {
			ip = request.getHeader("X-Forwarded-For");
		}

		if (ip == null || ip.length() == 0) {
			ip = request.getRemoteAddr();
		}

		return ip;
	}

	/**
	 * 获取用户数据对象
	 * 
	 * @return protected UserVo getCurrentUser(){ return (UserVo)
	 *         request.getAttribute(TSSystemConstant.REQUEST_USER); }
	 */

	protected void printSimpleResult(HttpServletResponse response, String responseText) {
		try {
			PrintWriter out = this.getPrintWriter(response);
			out.print(responseText);
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 获取页面输出对象
	 * 
	 * @param response
	 * @return
	 * @throws IOException
	 */
	protected PrintWriter getPrintWriter(HttpServletResponse response) throws IOException {
		// response.setCharacterEncoding("UTF-8");
		// response.setContentType("application/json;charset=UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		return response.getWriter();
	}
}
